/* 
 * File:   Storage.cpp
 * Author: Imre Tabur
 * 
 */
#include <boost/thread/mutex.hpp>
#include <vector>
#include "Storage.h"
#include "FileThread.h"

using namespace CloudyStorage;
using namespace std;

Storage * Storage::singletone = 0;
boost::mutex instanceMutex;

Storage::Storage() {
}

Storage::~Storage() {
    this->deleteThreads();
}

void Storage::stop() {
    vector<FileThread *>::iterator it;
    for (it = this->fileThreads.begin(); it < this->fileThreads.end(); it++) {
        FileThread * ft = *it;
        ft->stop();
    }
}

void Storage::join() {
    vector<FileThread *>::iterator it;
    for (it = this->fileThreads.begin(); it < this->fileThreads.end(); it++) {
        FileThread * ft = *it;
        ft->join();
    }
}

void Storage::deleteThreads() {
    vector<FileThread *>::iterator it;
    for (it = this->fileThreads.begin(); it < this->fileThreads.end(); it++) {
        FileThread * ft = *it;
        delete ft;
    }
    this->fileThreads.clear();
}

void Storage::closeConnectors() {
    vector<IConnector *>::iterator it;
    for (it = this->connectors.begin(); it < this->connectors.end(); it++) {
        IConnector * connector = *it;
        connector->close();
    }
}

void Storage::deleteConnectors() {
    vector<IConnector *>::iterator it;
    for (it = this->connectors.begin(); it < this->connectors.end(); it++) {
        IConnector * connector = *it;
        delete connector;
    }
}

Storage * Storage::instance() {
    {
        boost::mutex::scoped_lock singletoneLock(instanceMutex);
        if (singletone == 0) {
            Storage::singletone = new Storage();
        }
    }
    return Storage::singletone;
}

void Storage::push(const File &file) {

}

FileThread* Storage::pull(const char *name) {
    std::string nm = name;
    return this->pull(nm);
}

FileThread* Storage::pull(const std::string &name) {
    FileThread *fileThread = new FileThread();
    File *file = new File();
    fileThread->setFile(file);
    this->fileThreads.push_back(fileThread);
    fileThread->start();
    return fileThread;
}
